<?php

namespace App\Http\Controllers\Api;

use App\Activity;
use App\ActivityJoin;
use App\ActivityRefund;
use App\AppointExpert;
use App\BusinessSituationTemplate;
use App\BusinessSituationTemplateImg;
use App\Classify;
use App\Comment;
use App\DemandAllureLabel;
use App\DemandButt;
use App\DemandImg;
use App\Demands;
use App\ExpertLabel;
use App\ExpertQualificationImg;
use App\Experts;
use App\Files;
use App\Http\Services\BusinessLicense;
use App\Http\Services\CarBrandDiscern;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\Industries;
use App\JoinActivity;
use App\Message;
use App\News;
use App\NewsLabel;
use App\Orders;
use App\PersonalAuth;
use App\UnitAuth;
use App\UnitBusinessLabel;
use App\Units;
use App\UnitSettledApply;
use App\User;
use App\UserAttentionActivity;
use App\UserAttentionDemand;
use App\UserAttentionNews;
use App\UserInfo;
use App\UserVip;
use App\UserXUnit;
use App\VipPackageXRule;
use App\VipRule;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use DB;

class UCenterController extends Controller
{
    /**
     * 获取个人信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => '']);

        $userInfo = UserInfo::whereUserId($user->id)->first();
        if($userInfo){
            $userBasicInfo = CommonManager::getUserBasicInfo($user->id);
            if($userBasicInfo){
                $userInfo->photo_url        = $userBasicInfo['photo_url'];
                $userInfo->is_personal_auth = $userBasicInfo['is_personal_auth'];
                $userInfo->is_unit_auth     = $userBasicInfo['is_unit_auth'];
                $userInfo->is_expert_auth   = $userBasicInfo['is_expert_auth'];
                $userInfo->unit_name        = $userBasicInfo['unit_name'];
                $userInfo->is_vip           = $userBasicInfo['is_vip'];
                $userInfo->is_member_unit   = $userBasicInfo['is_member_unit'];
                $userInfo->is_official_unit = $userBasicInfo['is_official_unit'];
            }else{
                $userInfo->photo_url        = '';
                $userInfo->is_personal_auth = '';
                $userInfo->is_unit_auth     = '';
                $userInfo->is_expert_auth   = '';
                $userInfo->unit_name        = '';
                $userInfo->is_vip           = '';
                $userInfo->is_member_unit   = '';
                $userInfo->is_official_unit = '';
            }

            if($userInfo->realname != '' && !is_null($userInfo->realname)){
                $userInfo->nickname = $userInfo->realname;
            }else{
                if(is_null($userInfo->nickname) || $userInfo->nickname == ''){
                    $userInfo->nickname = '';
                }
            }

            if(is_null($userInfo->province) || $userInfo->province == ''){
                $userInfo->province = '';
            }

            if(is_null($userInfo->city) || $userInfo->city == ''){
                $userInfo->city = '';
            }

            if(is_null($userInfo->area) || $userInfo->area == ''){
                $userInfo->area = '';
            }

            if(is_null($userInfo->address) || $userInfo->address == ''){
                $userInfo->address = '';
            }

            $userInfo->vip_label = 0;

            $vipLAbelRule = VipRule::whereMark('vip_label')->first();
            if($vipLAbelRule){
                $userBindVipPackageList = CommonManager::judgeVipPackageXRule($vipLAbelRule->id,$user->id);
                if($userBindVipPackageList){
                    $userInfo->vip_label = 1;
                }
            }

            $userInfo->email = '';
            if($user->email != '' && !is_null($user->email)){
                $userInfo->email = $user->email;
            }

            if(!empty($userInfo->realname) && !empty($user->phone) && !empty($userInfo->company_name) && !empty($userInfo->position) && !empty($userInfo->industry_id) && !empty($user->email) && !empty($userInfo->province) && !empty($userInfo->city) && !empty($userInfo->area)){
                $userInfo->is_info_perfect = 1;
            }else{
                $userInfo->is_info_perfect = 0;
            }

            $userInfo->user_attention_demand_num = CommonManager::getUserAttentionDemandNum($user->id);
            $userInfo->user_attention_News_num = CommonManager::getUserAttentionNewsNum($user->id);
            $userInfo->user_attention_activity_num = CommonManager::getUserAttentionActivityNum($user->id);
            $userInfo->user_release_demand_num = CommonManager::getUserReleaseDemandNum($user->id);
            $userInfo->user_butt_demand_num = CommonManager::getUserButtDemandNum($user->id);
            $userInfo->user_join_activity_num = CommonManager::getUserJoinActivityNum($user->id);

            //个人认证状态
            $userInfo->personal_auth_status      = -1;
            $userInfo->personal_auth_status_name = '';
            $userInfo->new_personal_auth_status      = -1;
            $userInfo->new_personal_auth_status_name = '';
            //单位认证状态
            $userInfo->unit_auth_status      = -1;
            $userInfo->unit_auth_status_name = '';
            $userInfo->new_unit_auth_status      = -1;
            $userInfo->new_unit_auth_status_name = '';
            //专家认证状态
            $userInfo->expert_auth_status      = -1;
            $userInfo->expert_auth_status_name = '';
            $userInfo->new_expert_auth_status      = -1;
            $userInfo->new_expert_auth_status_name = '';

            /** @var PersonalAuth $personalAuth */
            $personalAuth = PersonalAuth::whereUserId($userInfo->user_id)->whereIn('is_auth',[1,3])->first();
            if($personalAuth){
                $userInfo->personal_auth_status      = $personalAuth->is_auth;
                if($personalAuth->is_auth == 1){
                    $userInfo->personal_auth_status_name = '已认证';
                }else{
                    $userInfo->personal_auth_status_name = CommonManager::getAuthReviewStatus($personalAuth->is_auth);
                }

                /** @var PersonalAuth $newPersonalAuth */
                $newPersonalAuth = PersonalAuth::whereUserId($userInfo->user_id)->where('id','>',$personalAuth->id)->orderBy('created_at','desc')->first();
                if($newPersonalAuth){
                    $userInfo->new_personal_auth_status = $newPersonalAuth->is_auth;
                    if($newPersonalAuth->is_auth == 1){
                        $userInfo->new_personal_auth_status_name = '已认证';
                    }else{
                        $userInfo->new_personal_auth_status_name = CommonManager::getAuthReviewStatus($newPersonalAuth->is_auth);
                    }
                }
            }else{
                $personalAuth = PersonalAuth::whereUserId($userInfo->user_id)->orderBy('created_at','desc')->first();
                if($personalAuth){
                    $userInfo->personal_auth_status      = $personalAuth->is_auth;
                    if($personalAuth->is_auth == 1){
                        $userInfo->personal_auth_status_name = '已认证';
                    }else{
                        $userInfo->personal_auth_status_name = CommonManager::getAuthReviewStatus($personalAuth->is_auth);
                    }
                }
            }

            /** @var UnitAuth $unitAuth */
            $unitAuth = UnitAuth::whereUserId($userInfo->user_id)->whereIn('is_auth',[1,3])->first();
            if($unitAuth){
                $userInfo->unit_auth_status      = $unitAuth->is_auth;
                if($unitAuth->is_auth == 1){
                    $userInfo->unit_auth_status_name = '已认证';
                }else{
                    $userInfo->unit_auth_status_name = CommonManager::getAuthReviewStatus($unitAuth->is_auth);
                }

                /** @var UnitAuth $newUnitAuth */
                $newUnitAuth = UnitAuth::whereUserId($userInfo->user_id)->where('id','>',$unitAuth->id)->orderBy('created_at','desc')->first();
                if($newUnitAuth){
                    $userInfo->new_unit_auth_status = $newUnitAuth->is_auth;
                    if($newUnitAuth->is_auth == 1){
                        $userInfo->new_unit_auth_status_name = '已认证';
                    }else{
                        $userInfo->new_unit_auth_status_name = CommonManager::getAuthReviewStatus($newUnitAuth->is_auth);
                    }
                }
            }else{
                $unitAuth = UnitAuth::whereUserId($userInfo->user_id)->orderBy('created_at','desc')->first();
                if($unitAuth){
                    $userInfo->unit_auth_status      = $unitAuth->is_auth;
                    if($unitAuth->is_auth == 1){
                        $userInfo->unit_auth_status_name = '已认证';
                    }else{
                        $userInfo->unit_auth_status_name = CommonManager::getAuthReviewStatus($unitAuth->is_auth);
                    }
                }
            }

            /** @var Experts $expertAuth */
            $expertAuth = Experts::whereUserId($userInfo->user_id)->whereIn('is_auth',[1,3])->first();
            if($expertAuth){
                $userInfo->expert_auth_status      = $expertAuth->is_auth;
                if($expertAuth->is_auth == 1){
                    $userInfo->expert_auth_status_name = '已认证';
                }else{
                    $userInfo->expert_auth_status_name = CommonManager::getAuthReviewStatus($expertAuth->is_auth);
                }

                /** @var Experts $newExpertAuth */
                $newExpertAuth = Experts::whereUserId($userInfo->user_id)->where('id','>',$expertAuth->id)->orderBy('created_at','desc')->first();
                if($newExpertAuth){
                    $userInfo->new_expert_auth_status = $newExpertAuth->is_auth;
                    if($newExpertAuth->is_auth == 1){
                        $userInfo->new_expert_auth_status_name = '已认证';
                    }else{
                        $userInfo->new_expert_auth_status_name = CommonManager::getAuthReviewStatus($newExpertAuth->is_auth);
                    }
                }
            }else{
                $expertAuth = Experts::whereUserId($userInfo->user_id)->orderBy('created_at','desc')->first();
                if($expertAuth){
                    $userInfo->expert_auth_status      = $expertAuth->is_auth;
                    if($expertAuth->is_auth == 1){
                        $userInfo->expert_auth_status_name = '已认证';
                    }else{
                        $userInfo->expert_auth_status_name = CommonManager::getAuthReviewStatus($expertAuth->is_auth);
                    }                }
            }

            $thisUnitSettledApply = UnitSettledApply::whereUserId($userInfo->user_id)->whereStatus(0)->first();
            if($thisUnitSettledApply){
                $userInfo->unit_settled_apply = 1;
            }else{
                $userInfo->unit_settled_apply = 0;
            }

        }

        $user->user_info = $userInfo;
        return response()->json(['level' => 'success','message' => '获取成功','data' => $user]);
    }

    /**
     * 设置个人信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUserInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $nickname             = !is_null($request->get('nickname')) ? $request->get('nickname') : '';
        $realname             = !is_null($request->get('realname')) ? $request->get('realname') : '';
        $phone                = !is_null($request->get('phone')) ? $request->get('phone') : '';
        $wechat               = !is_null($request->get('wechat')) ? $request->get('wechat') : '';
        $province             = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                 = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                 = !is_null($request->get('area')) ? $request->get('area') : '';
        $industryId           = !is_null($request->get('industry_id')) ? $request->get('industry_id') : 0;
        $photoId              = !is_null($request->get('photo_id')) ? $request->get('photo_id') : 0;
        $companyName          = !is_null($request->get('company_name')) ? $request->get('company_name') : '';
        $position             = !is_null($request->get('position')) ? $request->get('position') : '';
        $email                = !is_null($request->get('email')) ? $request->get('email') : '';

        if($realname == '')
            return response()->json(['level' => 'error','message' => '请填写姓名']);

        if($companyName == '')
            return response()->json(['level' => 'error','message' => '请填写所在企业']);

        if($position == '')
            return response()->json(['level' => 'error','message' => '请填写岗位']);

        if($industryId == '' || $industryId == 0)
            return response()->json(['level' => 'error','message' => '请选择行业']);

        if($province == '')
            return response()->json(['level' => 'error','message' => '请选择地区']);

        if($city == '')
            return response()->json(['level' => 'error','message' => '请选择地区']);

        if($area == '')
            return response()->json(['level' => 'error','message' => '请选择地区']);

        if($email == '')
            return response()->json(['level' => 'error','message' => '请填写邮箱']);

//        if($phone == '')
//            return response()->json(['level' => 'error','message' => '请授权手机号']);
//
//        $verificationPhone = CommonManager::phoneVerification($phone);
//        if(!$verificationPhone)
//            return response()->json(['level' => 'error','message' => '手机号格式不正确']);

        $userInfo = UserInfo::whereUserId($user->id)->first();
        if(!$userInfo)
            $userInfo = new UserInfo();

        $userInfo->user_id           = $user->id;
        if($photoId != 0 && $photoId != $userInfo->photo_id ){
            $userInfo->photo_id          = $photoId;
        }

        $userInfo->nickname            = $nickname;
        $userInfo->realname            = $realname;
        $userInfo->wechat                = $wechat;
        $userInfo->province            = $province;
        $userInfo->city                    = $city;
        $userInfo->area                    = $area;
        $userInfo->industry_id        = $industryId;
        $userInfo->company_name       = $companyName;
        $userInfo->position           = $position;
        $userInfo->save();

        $user->email                  = $email;
        $user->save();

        if(!empty($userInfo->realname) && !empty($user->phone) && !empty($userInfo->company_name) && !empty($userInfo->position) && !empty($userInfo->industry_id) && !empty($user->email) && !empty($userInfo->province) && !empty($userInfo->city) && !empty($userInfo->area)){
            $industry = Industries::whereId($industryId)->first();
            $industryName = $industry ? $industry->name : '';
            $clue = DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereContact($user->phone)->whereJoinRecycleBin(0)->first();
            if(!$clue){
                DB::connection('crm')->table('clues')->insert([
                    'name' => $userInfo->realname,
                    'contact' => $user->phone,
                    'province' => $userInfo->province,
                    'city' => $userInfo->city,
                    'area' => $userInfo->area,
                    'email' => $user->email,
                    'source' => 1,
                    'remark' => "岗位：". $position . '；行业：' . $industryName,
                    'synchronization_reason' => '完善资料',
                    'created_at' => date("Y-m-d H:i:s",time()),
                    'updated_at' => date("Y-m-d H:i:s",time()),
                ]);

                $clueStage = DB::connection('crm')->table('clue_stage')->whereNull('deleted_at')->whereSort(1)->first();
                if($clueStage){
                    DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereContact($user->phone)->where('synchronization_reason','like','%'.'完善资料'.'%')->orWhere('synchronization_reason','like','%'.'申请个人认证'.'%')->whereJoinRecycleBin(0)->update([
                        'clue_stage_id' => $clueStage->id,
                    ]);
                }
            }else{
                if($clue->synchronization_reason){
                    $str = mb_strpos($clue->synchronization_reason,'完善资料');

                    if($str !== false) {
                        $synchronizationReason = $clue->synchronization_reason;
                    }else{
                        $synchronizationReason = $clue->synchronization_reason . ',' . '完善资料';
                    }
                }else{
                    $synchronizationReason = '完善资料';
                }

                if($str !== false) {
                    DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereContact($user->phone)->where('synchronization_reason','like','%'.'完善资料'.'%')->orWhere('synchronization_reason','like','%'.'申请个人认证'.'%')->whereJoinRecycleBin(0)->update([
                        'name' => $userInfo->realname,
                        'province' => $userInfo->province,
                        'city' => $userInfo->city,
                        'area' => $userInfo->area,
                        'email' => $user->email,
                        'synchronization_reason' => $synchronizationReason,
                        'updated_at' => date("Y-m-d H:i:s", time()),
                    ]);
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $userInfo]);
    }

    /**
     * 获取个人认证信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPersonalAuthInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var PersonalAuth $personalAuth */
        $personalAuth = PersonalAuth::whereUserId($user->id)->whereIn('is_auth',[1,3])->first();
        if($personalAuth){
            $personalAuth->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $personalAuth]);
    }

    /**
     * 个人认证申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitPersonalAuth(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $realname             = !is_null($request->get('realname')) ? $request->get('realname') : '';
        $idCard               = !is_null($request->get('id_card')) ? $request->get('id_card') : '';
        $unitName             = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $job                  = !is_null($request->get('job')) ? $request->get('job') : '';
        $workImgId            = !is_null($request->get('work_img_id')) ? $request->get('work_img_id') : 0;

        $thisPersonalAuth = PersonalAuth::whereUserId($user->id)->whereIsAuth(0)->first();
        if($thisPersonalAuth)
            return response()->json(['level' => 'error','message' => '申请正在处理中']);

        if($realname == '')
            return response()->json(['level' => 'error','message' => '请输入真实姓名']);

        if($idCard == '')
            return response()->json(['level' => 'error','message' => '请输入身份证号']);

        $idCardVerification = CommonManager::idCardVerification($idCard);
        if(!$idCardVerification)
            return response()->json(['level' => 'error','message' => '身份证号格式不正确']);

        if($unitName == '')
            return response()->json(['level' => 'error','message' => '请输入单位名称']);

        $thisUnit = Units::whereName($unitName)->first();
        if(!$thisUnit)
            return response()->json(['level' => 'error','message' => '该单位不存在']);

        if($job == '')
            return response()->json(['level' => 'error','message' => '请输入岗位']);

        if($workImgId == 0)
            return response()->json(['level' => 'error','message' => '请上传在职证明']);

        $thatUnit = Units::whereName($unitName)->whereIsMemberUnit(1)->first();
        if(!$thatUnit){
            return response()->json(['level' => 'error','message' => '所在单位不存在或未成功入驻平台！']);
        }

        //判断是否优先审核
        $isPriorityReview = 0;
        $priorityReviewVipRule = VipRule::whereMark('priority_review')->first();
        if($priorityReviewVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($priorityReviewVipRule->id,$user->id);
            if($userBindVipPackageList){
                $isPriorityReview = 1;
            }
        }

        $personalAuth = new PersonalAuth();
        $personalAuth->user_id          = $user->id;
        $personalAuth->realname         = $realname;
        $personalAuth->id_card          = $idCard;
        $personalAuth->unit_name        = $unitName;
        $personalAuth->job              = $job;
        $personalAuth->work_img_id      = $workImgId;
        if($isPriorityReview == 1){
            $personalAuth->is_top       = 1;
        }
        $personalAuth->save();

        $newMessage = new Message();
        $newMessage->type        = 'admin';
        $newMessage->content     = $realname . '提交了个人认证申请';
        $newMessage->link_type   = 'personal_auth';
        $newMessage->link_id     = $personalAuth->id;
        $newMessage->save();

        $unitAdminUser = UserXUnit::whereUnitId($thatUnit->id)->whereIsAdmin(1)->first();
        if($unitAdminUser){
            $newMessage = new Message();
            $newMessage->type        = 'manager';
            $newMessage->content     = $realname . '提交了个人认证申请';
            $newMessage->link_type   = 'personal_auth_to_manager';
            $newMessage->link_id     = $thatUnit->id;
            $newMessage->to_user_id  = $unitAdminUser->user_id;
            $newMessage->save();
        }

        if($user->phone) {
            $clue = DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereContact($user->phone)->whereJoinRecycleBin(0)->first();
            if(!$clue){
                DB::connection('crm')->table('clues')->insert([
                    'name' => $personalAuth->realname,
                    'contact' => $user->phone,
                    'source' => 1,
                    'remark' => "单位名称：" . $unitName . "；岗位：" . $job,
                    'synchronization_reason' => '申请个人认证',
                    'created_at' => date("Y-m-d H:i:s",time()),
                    'updated_at' => date("Y-m-d H:i:s",time()),
                ]);

                $clueStage = DB::connection('crm')->table('clue_stage')->whereNull('deleted_at')->whereSort(1)->first();
                if($clueStage){
                    DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereContact($user->phone)->where('synchronization_reason','like','%'.'完善资料'.'%')->orWhere('synchronization_reason','like','%'.'申请个人认证'.'%')->whereJoinRecycleBin(0)->update([
                        'clue_stage_id' => $clueStage->id,
                    ]);
                }
            }else{
                if($clue->synchronization_reason){
                    $str = mb_strpos($clue->synchronization_reason,'申请个人认证');

                    if($str !== false){
                        $synchronizationReason = $clue->synchronization_reason;
                    }else{
                        $synchronizationReason = $clue->synchronization_reason . ',' . '申请个人认证';
                    }
                }else{
                    $synchronizationReason = '申请个人认证';
                }
                $str2 = mb_strpos($clue->synchronization_reason,'入会申请');

                if($str2 === false) {
                    DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereContact($user->phone)->where('synchronization_reason','like','%'.'完善资料'.'%')->orWhere('synchronization_reason','like','%'.'申请个人认证'.'%')->whereJoinRecycleBin(0)->update([
                        'name' => $personalAuth->realname,
                        'synchronization_reason' => $synchronizationReason,
                    ]);
                }
            }
        }

        return response()->json(['level' => 'success','message' => '提交成功','data' => $personalAuth]);
    }

    /**
     * 获取单位认证信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitAuthInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var UnitAuth $unitAuth */
        $unitAuth = UnitAuth::whereUserId($user->id)->whereIn('is_auth',[1,3])->first();
        if($unitAuth){
            $unitAuth->license_img_url = FileManager::getImgUrl($unitAuth->license_img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitAuth]);
    }

    /**
     * 单位认证申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitUnitAuth(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $realname                 = !is_null($request->get('realname')) ? $request->get('realname') : '';
        $unitName                 = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $uniformSocialCreditCode  = !is_null($request->get('uniform_social_credit_code')) ? $request->get('uniform_social_credit_code') : '';
        $province                 = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                     = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                     = !is_null($request->get('area')) ? $request->get('area') : '';
        $address                  = !is_null($request->get('address')) ? $request->get('address') : '';
        $licenseImgId             = !is_null($request->get('license_img_id')) ? $request->get('license_img_id') : 0;

        $thisUnitAuth = UnitAuth::whereUserId($user->id)->whereIsAuth(0)->first();
        if($thisUnitAuth)
            return response()->json(['level' => 'error','message' => '申请正在处理中']);

        if($unitName == '')
            return response()->json(['level' => 'error','message' => '请填写公司名称']);

        if($uniformSocialCreditCode == '')
            return response()->json(['level' => 'error','message' => '请填写社会信用代码']);

        $uniformSocialCreditCodeVerification = CommonManager::uniformSocialCreditCodeVerification($uniformSocialCreditCode);
        if(!$uniformSocialCreditCodeVerification)
            return response()->json(['level' => 'error','message' => '社会信用代码格式不正确']);

        if($province == '')
            return response()->json(['level' => 'error','message' => '请选择单位地址']);

        if($realname == '')
            return response()->json(['level' => 'error','message' => '请输入真实姓名']);

        if($city == '')
            return response()->json(['level' => 'error','message' => '请选择单位地址']);

        if($area == '')
            return response()->json(['level' => 'error','message' => '请选择单位地址']);

        if($address == '')
            return response()->json(['level' => 'error','message' => '请填写单位详细信息']);

        if($licenseImgId == 0)
            return response()->json(['level' => 'error','message' => '请传入营业执照']);

        //判断是否优先审核
        $isPriorityReview = 0;
        $priorityReviewVipRule = VipRule::whereMark('priority_review')->first();
        if($priorityReviewVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($priorityReviewVipRule->id,$user->id);
            if($userBindVipPackageList){
                $isPriorityReview = 1;
            }
        }

        $newUnitAuth = new UnitAuth();
        $newUnitAuth->user_id                     = $user->id;
        $newUnitAuth->name                        = $unitName;
        $newUnitAuth->realname                    = $realname;
        $newUnitAuth->uniform_social_credit_code  = $uniformSocialCreditCode;
        $newUnitAuth->province                    = $province;
        $newUnitAuth->city                        = $city;
        $newUnitAuth->area                        = $area;
        $newUnitAuth->address                     = $address;
        $newUnitAuth->license_img_id              = $licenseImgId;
        if($isPriorityReview == 1){
            $newUnitAuth->is_top                  = 1;
        }
        $newUnitAuth->save();

        return response()->json(['level' => 'success','message' => '提交成功','data' => $newUnitAuth]);
    }

    /**
     * 湖区专家认证信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertAuthInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var Experts $unitAuth */
        $expertAuth = Experts::whereUserId($user->id)->whereIn('is_auth',[1,3])->first();
        if($expertAuth){
            $expertAuth->photo_url = FileManager::getImgUrl($expertAuth->photo_id);
            $expertAuth->expert_label = CommonManager::getExpertLabel($expertAuth->id);
            $expertAuth->expert_qualification_img = CommonManager::getExpertQualificationImg($expertAuth->id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expertAuth]);
    }

    /**
     * 专家认证申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitExpertAuth(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $realname             = !is_null($request->get('realname')) ? $request->get('realname') : '';
        $photoId              = !is_null($request->get('photo_id')) ? $request->get('photo_id') : 0;
        $unitName             = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $position             = !is_null($request->get('position')) ? $request->get('position') : '';
        $province             = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                 = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                 = !is_null($request->get('area')) ? $request->get('area') : '';
        $strengths            = !is_null($request->get('strengths')) ? $request->get('strengths') : '';
        $labels               = $request->get('labels');
        $qualificationImgs    = $request->get('qualification_imgs');

        $thisExpertAuth = Experts::whereUserId($user->id)->whereIsAuth(0)->first();
        if($thisExpertAuth)
            return response()->json(['level' => 'error','message' => '申请正在处理中']);

        if($realname == '')
            return response()->json(['level' => 'error','message' => '请输入真实姓名']);

        if($photoId == 0)
            return response()->json(['level' => 'error','message' => '请传入专家头像']);

        if($unitName == '')
            return response()->json(['level' => 'error','message' => '请输入单位明恒']);

        if($position == '')
            return response()->json(['level' => 'error','message' => '请输入职称']);

        if($province == '')
            return response()->json(['level' => 'error','message' => '请选择城市']);

        if($city == '')
            return response()->json(['level' => 'error','message' => '请选择城市']);

        if($area == '')
            return response()->json(['level' => 'error','message' => '请选择城市']);

        if($strengths == '')
            return response()->json(['level' => 'error','message' => '请输入擅长领域']);

        if(!is_array($labels) || (is_array($labels) && count($labels) <= 0))
            return response()->json(['level' => 'error','message' => '请填写专家标签']);

        if(!is_array($qualificationImgs) || (is_array($qualificationImgs) && count($qualificationImgs) <= 0))
            return response()->json(['level' => 'error','message' => '请传入资质证明']);

        //判断是否优先审核
        $isPriorityReview = 0;
        $priorityReviewVipRule = VipRule::whereMark('priority_review')->first();
        if($priorityReviewVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($priorityReviewVipRule->id,$user->id);
            if($userBindVipPackageList){
                $isPriorityReview = 1;
            }
        }

        $expert = new Experts();
        $expert->user_id             = $user->id;
        $expert->realname            = $realname;
        $expert->photo_id            = $photoId;
        $expert->unit_name           = $unitName;
        $expert->position            = $position;
        $expert->province            = $province;
        $expert->city                = $city;
        $expert->area                = $area;
        $expert->strengths           = $strengths;
        if($isPriorityReview == 1){
            $expert->is_top          = 1;
        }
        $expert->save();

        foreach($labels as $label){
            $newExpertLabel = new ExpertLabel();
            $newExpertLabel->expert_id    = $expert->id;
            $newExpertLabel->name         = $label;
            $newExpertLabel->save();
        }

        foreach($qualificationImgs as $qualificationImg){
            $newQualificationImgs = new ExpertQualificationImg();
            $newQualificationImgs->expert_id        = $expert->id;
            $newQualificationImgs->img_id           = $qualificationImg;
            $newQualificationImgs->save();
        }
        $newMessage = new Message();
        $newMessage->type          = 'admin';
        $newMessage->content       = $realname . '提交了专家认认证申请';
        $newMessage->link_type     = 'expert_auth';
        $newMessage->link_id       = $expert->id;
        $newMessage->save();

        return response()->json(['level' => 'success','message' => '提交成功','data' => $expert]);
    }

    /**
     * 获取我关注的活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserAttentionActivityList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        /** @var UserAttentionActivity $getActivityId */
        $getActivityIdArr = UserAttentionActivity::whereUserId($user->id);

        $pageInfo['total'] =$getActivityIdArr->count();

        $getActivityIdArr = $getActivityIdArr->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($getActivityIdArr) > 0){
            foreach($getActivityIdArr as $getActivityId){
                $activity = DB::table('activity')->whereId($getActivityId->activity_id)->first();
                if($activity){
                    $activity->activity_Join_num = CommonManager::getActivityJoinNum($activity->id);
                    $activity->img_url   = FileManager::getImgUrl($activity->img_id);
                    $activity->week    = date("W",strtotime($activity->start_time));
                    $activity->share_img_url = FileManager::getImgUrl($activity->share_img_id);
                    $activity->sign_img_url = FileManager::getImgUrl($activity->sign_qr_code_img_id);
                    //当前时间
                    $time = date('Y-m-d H:i:s',time());

                    if($time < $activity->start_time){
                        $conduct = '报名中';
                        $activityStatus = 1;
                    }elseif($time > $activity->end_time){
                        $conduct = '已结束';
                        $activityStatus = 3;
                    }else{
                        $conduct = '进行中';
                        $activityStatus = 2;
                    }
                    $activity->activity_status = $activityStatus;
                    $activity->activity_status_name = $conduct;

                    $activeParty = CommonManager::getActivePartyInfo($activity->active_party_id);
                    $activity->active_party_Info = $activeParty;

                    $activity->activity_url = '/pages/details/activityDetail/activityDetail?activityId=' . $activity->id;

                    if($user){
                        /** @var ActivityJoin $thisJoinActivity */
                        $thisJoinActivity = ActivityJoin::whereUserId($user->id)->whereActivityId($activity->id)->whereStatus(1)->first();
                        if($thisJoinActivity){
                            $activity->is_join = 1;
                        }else{
                            $activity->is_join = 2;
                        }

                        $thisUserCollection = UserAttentionActivity::whereUserId($user->id)->whereActivityId($activity->id)->first();
                        if($thisUserCollection){
                            $activity->is_collection = 1;
                        }else{
                            $activity->is_collection = 2;
                        }
                    }else{
                        $activity->is_join       = null;
                        $activity->is_collection = null;

                    }
                }
                $getActivityId->activity_info = $activity;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $getActivityIdArr,'page_info' => $pageInfo]);
    }

    /**
     * 获取营业执照信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBusinessLicenseInfo(Request $request){
        $imgId = !is_null($request->get('img_id')) ? $request->get('img_id') : 0;

        $unitInfo = CommonManager::getUnitInfoToImg($imgId);

        if(!empty($unitInfo)){
            $province = '';
            $city = '';
            $area = '';
            $address = '';

            if(!empty($unitInfo->f)){
                $provinceCount = mb_strpos($unitInfo->f,'省');
                if($provinceCount != false){
                    $provinceCount += 1;
                    $provinceStr = mb_substr($unitInfo->f,0,$provinceCount,'utf-8');
                    if($provinceStr != false){
                        $province = $provinceStr;
                    }
                }

                $cityCount = mb_strpos($unitInfo->f,'市');
                if($cityCount != false){
                    $cityCount += 1;

                    if($provinceCount != false){
                        $provinceLength = $cityCount - $provinceCount;

                        $cityStr = mb_substr($unitInfo->f,$provinceCount,$provinceLength,'utf-8');
                    }else{
                        $cityStr = mb_substr($unitInfo->f,0,$cityCount,'utf-8');
                    }

                    if($cityStr != false){
                        $city = $cityStr;
                    }
                }

                $areaCount = mb_strpos($unitInfo->f,'区');
                if($areaCount != false){
                    $areaCount += 1;

                    if($cityCount != false){
                        $areaLength = $areaCount - $cityCount;

                        $areaStr = mb_substr($unitInfo->f,$cityCount,$areaLength,'utf-8');
                    }else{
                        $areaStr = mb_substr($unitInfo->f,0,$areaCount,'utf-8');
                    }

                    if($areaStr != false){
                        $area = $areaStr;
                    }

                    $addressStr = mb_substr($unitInfo->f,$areaCount,null,'utf-8');
                    if($addressStr != false){
                        $address = $addressStr;
                    }
                }else {
                    $areaCount = mb_strpos($unitInfo->f, '县');
                    if ($areaCount != false) {
                        $areaCount += 1;

                        if ($cityCount != false) {
                            $areaLength = $areaCount - $cityCount;

                            $areaStr = mb_substr($unitInfo->f, $cityCount, $areaLength, 'utf-8');
                        } else {
                            $areaStr = mb_substr($unitInfo->f, 0, $areaCount, 'utf-8');
                        }

                        if ($areaStr != false) {
                            $area = $areaStr;
                        }

                        $addressStr = mb_substr($unitInfo->f, $areaCount, null, 'utf-8');
                        if ($addressStr != false) {
                            $address = $addressStr;
                        }
                    }else{
                        $areaCount = mb_strpos($unitInfo->f, '乡');
                        if ($areaCount != false) {
                            $areaCount += 1;

                            if ($cityCount != false) {
                                $areaLength = $areaCount - $cityCount;

                                $areaStr = mb_substr($unitInfo->f, $cityCount, $areaLength, 'utf-8');
                            } else {
                                $areaStr = mb_substr($unitInfo->f, 0, $areaCount, 'utf-8');
                            }

                            if ($areaStr != false) {
                                $area = $areaStr;
                            }

                            $addressStr = mb_substr($unitInfo->f, $areaCount, null, 'utf-8');
                            if ($addressStr != false) {
                                $address = $addressStr;
                            }
                        }
                    }
                }
            }

            $unitAddress = (object)['province' => $province,'city' => $city,'area' => $area,'address' => $address];

            return response()->json(['level' => 'success','message' => '获取成功','data' => $unitInfo,'unit_address' => $unitAddress]);
        }else{
            return response()->json(['level' => 'error','message' => '获取失败']);
        }
    }

    /**
     * 单位入驻申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitUnitSettledApply(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $unitName                 = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $photoId                  = !is_null($request->get('logo_id')) ? $request->get('logo_id') : 0;
        $uniformSocialCreditCode  = !is_null($request->get('uniform_social_credit_code')) ? $request->get('uniform_social_credit_code') : '';
        $province                 = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                     = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                     = !is_null($request->get('area')) ? $request->get('area') : '';
        $address                  = !is_null($request->get('address')) ? $request->get('address') : '';
        $licenseImgId             = !is_null($request->get('license_img_id')) ? $request->get('license_img_id') : 0;
        $contactNumber            = !is_null($request->get('contact_number')) ? $request->get('contact_number') : '';
        $introduction             = !is_null($request->get('introduction')) ? $request->get('introduction') : '';
        $businessScope            = $request->get('business_scope');
        $contactPerson            = $request->get('contact_person');
        $email                    = $request->get('email');
        $isUnitAdmin              = !is_null($request->get('is_unit_admin')) ? $request->get('is_unit_admin') : 0;

//        $isPersonAuth = CommonManager::isPersonalAuth($user->id);
//        if(!$isPersonAuth)
//            return response()->json(['level' => 'error','message' => '请先完成个人认证']);

        if($unitName == '')
            return response()->json(['level' => 'error','message' => '请填写公司名称']);

        if($uniformSocialCreditCode == '')
            return response()->json(['level' => 'error','message' => '请填写社会信用代码']);
        if ($contactPerson=='')
            return response()->json(['level' => 'error','message' => '请输入联系人']);
        if ($email=='')
            return response()->json(['level' => 'error','message' => '请输入联系邮箱']);
        if($photoId == 0)
            return response()->json(['level' => 'error','message' => '请上传单位logo']);

        if($contactNumber == '')
            return response()->json(['level' => 'error','message' => '请填写联系电话']);

        if(!preg_match("/^(1[3456789])[0-9]{9}$/", $contactNumber))
            return response()->json(['level' => 'error','message' => '联系方式需为手机号码，请正确填写！']);

        if($province == '')
            return response()->json(['level' => 'error','message' => '请选择单位地址']);

        if($city == '')
            return response()->json(['level' => 'error','message' => '请选择单位地址']);

        if($area == '')
            return response()->json(['level' => 'error','message' => '请选择单位地址']);

        if($address == '')
            return response()->json(['level' => 'error','message' => '请填写单位详细信息']);

        if($licenseImgId == 0)
            return response()->json(['level' => 'error','message' => '请传入营业执照']);

        $uniformSocialCreditCodeVerification = CommonManager::uniformSocialCreditCodeVerification($uniformSocialCreditCode);
        if(!$uniformSocialCreditCodeVerification)
            return response()->json(['level' => 'error','message' => '社会信用代码格式不正确']);

        $isMemberUnit = Units::whereUniformSocialCreditCode($uniformSocialCreditCode)->whereIsMemberUnit(1)->first();
        if($isMemberUnit)
            return response()->json(['level' => 'error','message' => '该单位已是会员单位']);

        $thisUnitSettledApply = UnitSettledApply::whereUniformSocialCreditCode($uniformSocialCreditCode)->whereStatus(0)->first();
        if($thisUnitSettledApply)
            return response()->json(['level' => 'error','message' => '申请正在处理中']);

        $unitSettledApplyPass = UnitSettledApply::whereUniformSocialCreditCode($uniformSocialCreditCode)->whereStatus(1)->first();
        if($unitSettledApplyPass)
            return response()->json(['level' => 'error','message' => '单位入驻已通过']);
        if ($isUnitAdmin){
            $exist=UserXUnit::whereUserId($user->id)->whereIsAdmin(1)->first();
            if ($exist)
                return response()->json(['level' => 'error','message' => '当前帐号已成为其他单位的管理员']);
        }
//        if($introduction == '')
//            return response()->json(['level' => 'error','message' => '请填写企业简介']);
//
//        if(!is_array($businessScope) || (is_array($businessScope) && count($businessScope) <= 0))
//            return response()->json(['level' => 'error','message' => '请填写业务范围']);

        if(is_null($user->phone) || trim($user->phone) == ""){
            $user->phone = $contactNumber;
            $user->save();
        }

        //判断是否优先审核
        $isPriorityReview = 0;
        $priorityReviewVipRule = VipRule::whereMark('priority_review')->first();
        if($priorityReviewVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($priorityReviewVipRule->id,$user->id);
            if($userBindVipPackageList){
                $isPriorityReview = 1;
            }
        }


        $newUnitSettledApply = new UnitSettledApply();
        $newUnitSettledApply->user_id                     = $user->id;
        $newUnitSettledApply->photo_id                    = $photoId;
        $newUnitSettledApply->name                        = $unitName;
        $newUnitSettledApply->uniform_social_credit_code  = $uniformSocialCreditCode;
        $newUnitSettledApply->province                    = $province;
        $newUnitSettledApply->city                        = $city;
        $newUnitSettledApply->area                        = $area;
        $newUnitSettledApply->address                     = $address;
        $newUnitSettledApply->license_img_id              = $licenseImgId;
        $newUnitSettledApply->contact_number              = $contactNumber;
        $newUnitSettledApply->introduction                = $introduction;
        $newUnitSettledApply->email                       = $email;
        $newUnitSettledApply->contact_person              = $contactPerson;
        if($isPriorityReview == 1){
            $newUnitSettledApply->is_top                  = 1;
        }
        $newUnitSettledApply->is_unit_admin               = $isUnitAdmin;
        $newUnitSettledApply->save();

//        foreach($businessScope as $val){
//            $newUnitBusinessLabel = new UnitBusinessLabel();
//            $newUnitBusinessLabel->user_id                 = $user->id;
//            $newUnitBusinessLabel->unit_settled_apply_id   = $newUnitSettledApply->id;
//            $newUnitBusinessLabel->name                    = $val;
//            $newUnitBusinessLabel->save();
//        }

        $newMessage = new Message();
        $newMessage->type          = 'admin';
        $newMessage->content       = $unitName . '申请入驻平台';
        $newMessage->link_type     = 'company_set';
        $newMessage->link_id       = $newUnitSettledApply->id;
        $newMessage->save();

        $clue = DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereName($newUnitSettledApply->name)->whereJoinRecycleBin(0)->first();
        if(!$clue){
            DB::connection('crm')->table('clues')->insert([
                'name' => $newUnitSettledApply->name,
                'contact' => $newUnitSettledApply->contact_number,
                'province' => $newUnitSettledApply->province,
                'city' => $newUnitSettledApply->city,
                'area' => $newUnitSettledApply->area,
                'email' => $newUnitSettledApply->email,
                'source' => 1,
                'synchronization_reason' => '申请入会',
                'created_at' => date("Y-m-d H:i:s",time()),
                'updated_at' => date("Y-m-d H:i:s",time()),
            ]);

            $clueStage = DB::connection('crm')->table('clue_stage')->whereNull('deleted_at')->whereSort(1)->first();
            if($clueStage){
                DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereName($newUnitSettledApply->name)->whereJoinRecycleBin(0)->update([
                    'clue_stage_id' => $clueStage->id,
                ]);
            }
        }else{
            DB::connection('crm')->table('clues')->whereNull('deleted_at')->whereName($newUnitSettledApply->name)->whereJoinRecycleBin(0)->update([
                'contact' => $newUnitSettledApply->contact_number,
                'province' => $newUnitSettledApply->province,
                'city' => $newUnitSettledApply->city,
                'area' => $newUnitSettledApply->area,
                'email' => $newUnitSettledApply->email,
                'updated_at' => date("Y-m-d H:i:s",time()),
            ]);
        }


        return response()->json(['level' => 'success','message' => '提交成功','data' => $newUnitSettledApply]);
    }

    /**
     * 获取专家库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertsList(Request $request){
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;
        $keyword       = !is_null($request->get('keyword')) ? $request->get('keyword') : '';

//        $limit = 50;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        $page = $page - 1;
        $expertList = CommonManager::getExpertInfoList('app','list',$keyword,$limit,$page,1);
        $pageInfo['total'] = CommonManager::getExpertInfoDNum($keyword,1);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expertList,'page_info' => $pageInfo]);
    }

    /**
     * 获取专家详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertDetail(Request $request){
        $user = UserManager::isLogin($request);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $userId = 0;
        if($user){
            $userId = $user->id;
        }

        $expert = CommonManager::getExpertInfoList('app','detail','',0,0,1,$id,$userId);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expert]);
    }

    /**
     * 获取会员单位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMemberUnitList(Request $request){
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;
        $keyword       = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $classifyId    = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $unitGradeId   = !is_null($request->get('unit_grade_id')) ? $request->get('unit_grade_id') : 0;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        $page = $page - 1;
        $memberUnitList = CommonManager::getAllUnitInfoList('list',1,$keyword,$limit,$page,0,0,$classifyId,$unitGradeId);

        $pageInfo['total']  = CommonManager::getAllUnitInfoNum(1,$keyword);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $memberUnitList,'page_info' => $pageInfo]);
    }

    /**
     * 获取单位详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMemberUnitDetail(Request $request){
        $user = UserManager::isLogin($request);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $userId = 0;
        if($user){
            $userId = $user->id;
        }

        $memberUnit = CommonManager::getAllUnitInfoList('detail',1,'',0,0,$id,$userId);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $memberUnit]);
    }

    /**
     * 获取单位下的员工参与的需求
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitXUserDemandList(Request $request){
        $unitId = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;
        $page       =!is_null($request->get('page'))    ? $request->get('page')     : 1;
        $limit      =!is_null($request->get('limit'))   ? $request->get('limit')    : 10;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        /** @var User $user */
        $user = UserManager::isLogin($request);

        $unitXUserIds = UserXUnit::whereUnitId($unitId)->pluck('user_id');

        $demandIds = DemandButt::whereIn('user_id',$unitXUserIds)->pluck('demand_id');

        $demands=Demands::whereIn('id',$demandIds)->whereIsShop(1)->whereReview(1);

        $page_info['total']=$demands->count();

        $demands=$demands->orderBy('created_at','desc')->offset(($page - 1) * $limit)->limit($limit)->get();
        $url_array=[];

        if (count($demands) > 0){
            /** @var Demands $demand */
            foreach ($demands as $demand){
                $url_array=[];
                $classify   =Classify::whereId($demand->classify_id)    ->first();
                $industry   =Industries::whereId($demand->industry_id)  ->first();
                $imgs       =DemandImg::whereDemandId($demand->id)      ->get();
                $label      =DemandAllureLabel::whereDemandId($demand->id)->pluck('name')->toArray();

                if (count($imgs) > 0){
                    /** @var DemandImg $img */
                    foreach ($imgs as $img){
                        $url=FileManager::getImgUrl($img->img_id);
                        array_push($url_array,$url);
                    }
                }
                $demand->classify_name  = $classify ? $classify->name :'其他';
                $demand->industry_name  = $industry ? $industry->name :'其他';
                $demand->img_array_url  = $url_array;
                $demand->label_arr      = $label;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;

            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$demands]);
    }

    /**
     * 我参与的活动列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserJoinActivityList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 0;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var ActivityJoin $userJoinActivity */
        $userJoinActivityList = ActivityJoin::whereUserId($user->id);

        $pageInfo['total'] = $userJoinActivityList->count();

        $userJoinActivityList = $userJoinActivityList->whereStatus(1)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        if(count($userJoinActivityList) > 0){
            foreach($userJoinActivityList as $userJoinActivity){
                $thisActivity =  CommonManager::getActivityList('detail',0,0,'','',0,0,1,$user,$userJoinActivity->activity_id);

                $userJoinActivity->activity_info = $thisActivity;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userJoinActivityList,'page_info' => $pageInfo]);
    }
    public function getMyFavoriteNews(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];
        $page=$page-1;
        $userFavoriteNewsIds=UserAttentionNews::whereUserId($user->id)->pluck('news_id')->toArray();
        $userFavoriteNews   =News::withTrashed()->whereIn('id',$userFavoriteNewsIds);

        $pageInfo['total']  =$userFavoriteNews->count();

        $userFavoriteNews = $userFavoriteNews->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
        if (count($userFavoriteNews) > 0){
            /** @var News $item */
            foreach ($userFavoriteNews as $item){
                $comments=Comment::whereNewsId($item->id)->whereType('news')->whereStatus(1)
                    ->orderBy('created_at','desc')->orderBy('is_official','desc')->offset(0)->limit(5)->get();
                if (count($comments) > 0){
                    foreach ($comments as $comment){
                        $user_info=CommonManager::getUserBasicInfo($comment->user_id);
                        if ($user_info)
                            $comment->user_info=$user_info;
                        else
                            $comment->user_info=[];
                    }
                }
                $item->img_url          =FileManager::getImgUrl($item->img_id);
                $item->advert_img_url   =FileManager::getImgUrl($item->advert_img_id);
                $item->video_url        =FileManager::getVideoUrl($item->video_id);
                $item->lable_array      =NewsLabel::whereNewsId($item->id)->pluck('name')->toArray();
                $item->is_collection    = $user ? (UserAttentionNews::whereUserId($user->id)->whereNewsId($item->id)->first() ? 1 :2 ) : 2;
                $item->comments         =$comments;
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$pageInfo,'data'=>$userFavoriteNews]);
    }

    public function getMyFavoriteDemand(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];
        $page=$page-1;
        $pageInfo['total']  =UserAttentionDemand::whereUserId($user->id)->count();
        $demand_ids         =UserAttentionDemand::whereUserId($user->id)->offset($page * $limit)->limit($limit)->pluck('demand_id')->toArray();
        $demands            =Demands::withTrashed()->whereIn('id',$demand_ids)->get();
//        $delete_demand_ids  =Demands::onlyTrashed()->pluck('id')->toArray();
//        $UAD                =UserAttentionDemand::whereIn('demand_id',$delete_demand_ids)->delete();
        if (count($demands) > 0){
            /** @var Demands $demand */
            foreach ($demands as $demand){
                $url_array=[];
                $classify   =Classify::whereId($demand->classify_id)    ->first();
                $industry   =Industries::whereId($demand->industry_id)  ->first();
                $imgs       =DemandImg::withTrashed()->whereDemandId($demand->id)      ->get();
                $label      =DemandAllureLabel::withTrashed()->whereDemandId($demand->id)->pluck('name')->toArray();

                if (count($imgs) > 0){
                    /** @var DemandImg $img */
                    foreach ($imgs as $img){
                        $url=FileManager::getImgUrl($img->img_id);
                        array_push($url_array,$url);
                    }
                }
                $demand->classify_name  = $classify ? $classify->name :'其他';
                $demand->industry_name  = $industry ? $industry->name :'其他';
                $demand->img_array_url  = $url_array;
                $demand->label_arr      = $label;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$pageInfo,'data'=>$demands]);
    }

    /**
     * 设置业务情况模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setBusinessSituationTemplate(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        $id       = $request->get('id') ? $request->get('id') : 0;
        $content  = $request->get('content');
        $img_ids  = $request->get('img_ids');
        $phone    = $request->get('phoneNumber');
        $weChat   = $request->get('wechat_Number');
        $email    = $request->get('E_mail');

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        $isPHone = CommonManager::phoneVerification($phone);
        if(!$isPHone)
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if(is_null($weChat) || $weChat == '')
            return response()->json(['level' => 'error','message' => '请填写微信号']);

        if(is_null($email) || $email == '')
            return response()->json(['level' => 'error','message' => '请填写邮箱']);

        $isEmail = CommonManager::emailVerification($email);
        if(!$isEmail)
            return response()->json(['level' => 'error','message' => '邮箱格式不正确']);

        if (!$content)
            return response()->json(['level' => 'error','message' => '填写内容后才能保存哦','data' => []]);
        $template=BusinessSituationTemplate::whereId($id)->first();
        if (!$template){
            $template=new BusinessSituationTemplate();
            $template->user_id=$user->id;
        }
        if ($template->user_id!=$user->id)
            return response()->json(['level' => 'error','message' => '该模板不属于当前用户','data' => []]);
        $template->content = $content;
        $template->phone   = $phone;
        $template->wechat  = $weChat;
        $template->email   = $email;
        $template->save();
        if (count($img_ids)>0){
            $exist_img_ids  =BusinessSituationTemplateImg::whereBusinessSituationTemplateId($template->id)->pluck('img_id')->toArray();
            $remove_img_ids =array_diff($exist_img_ids,$img_ids);
            $add_img_ids    =array_diff($img_ids,$exist_img_ids);
            if (count($remove_img_ids) > 0)
                BusinessSituationTemplateImg::whereBusinessSituationTemplateId($template->id)->whereIn('img_id',$remove_img_ids)->delete();
            if (count($add_img_ids) > 0){
                foreach ($add_img_ids as $add_img_id){
                    if ($add_img_id){
                        $new_img= new BusinessSituationTemplateImg();
                        $new_img->business_situation_template_id=$template->id;
                        $new_img->img_id=$add_img_id;
                        $new_img->save();
                    }

                }
            }
        } else {
            BusinessSituationTemplateImg::whereBusinessSituationTemplateId($template->id)->delete();
        }
        return response()->json(['level'=>'success','message'=>'保存成功']);
    }

    public function getBusinessSituationTemplate(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        $page       =!is_null($request->get('page'))    ? $request->get('page')     : 1;
        $limit      =!is_null($request->get('limit'))   ? $request->get('limit')    : 10;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $id     =$request->get('id') ? $request->get('id') : 0;
        if ($id){
            $template=BusinessSituationTemplate::whereId($id)->whereUserId($user->id)->first();
            if (!$template)
                return response()->json(['level'=>'error','message'=>'模板不存在','data'=>[]]);
            $img_infos=BusinessSituationTemplateImg::whereBusinessSituationTemplateId($template->id)->get();
            if (count($img_infos) >0){
                foreach ($img_infos as $img_info){
                    $img_info->img_url=FileManager::getImgUrl($img_info->img_id);
                }
            }
            $template->img_info=$img_infos;

        } else {
            $template=BusinessSituationTemplate::whereUserId($user->id)->offset($page *$limit)->limit($limit)->get();
            $page_info['total']=BusinessSituationTemplate::whereUserId($user->id)->count();
            if (count($template) >0){
                foreach ($template as $item){
                    $img_infos=BusinessSituationTemplateImg::whereBusinessSituationTemplateId($item->id)->get();
                    if (count($img_infos) >0){
                        foreach ($img_infos as $img_info){
                            $img_info->img_url=FileManager::getImgUrl($img_info->img_id);
                        }
                    }
                    $item->img_info=$img_infos;

                }
            }

        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$template]);
    }
    public function delBusinessSituationTemplate(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        $id     =$request->get('id') ? $request->get('id') : 0;
        if ($id){
            $template=BusinessSituationTemplate::whereId($id)->whereUserId($user->id)->first();
            if (!$template)
                return response()->json(['level'=>'error','message'=>'模板不存在']);

            BusinessSituationTemplateImg::whereBusinessSituationTemplateId($template->id)->delete();
            $template->delete();
        } else {
            return response()->json(['level'=>'error','message'=>'参数错误']);
        }

        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    /**
     * 用户预约专家
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userAppointExpert(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        $user_name      =$request->get('user_name');
        $contact_phone  =$request->get('contact_phone');
        $expert_id      =$request->get('expert_id');
        $desc           =$request->get('desc');
        if (!$user_name)
            return response()->json(['level'=>'error','message'=>'请输入联系人姓名']);
        if (!$contact_phone)
            return response()->json(['level'=>'error','message'=>'请输入联系方式']);
        $expert=Experts::whereId($expert_id)->first();
        if (!$expert)
            return response()->json(['level'=>'error','message'=>'专家不存在']);
        $exist=AppointExpert::whereUserId($user->id)->whereExpertId($expert->id)->whereStatus(0)->first();
        if ($exist)
            return response()->json(['level'=>'error','message'=>'您已预约该专家，请耐心等待']);
        $appoint_expert =new AppointExpert();
        $appoint_expert->user_id        =$user->id;
        $appoint_expert->user_name      =$user_name;
        $appoint_expert->contact_phone  =$contact_phone;
        $appoint_expert->expert_id      =$expert->id;
        if ($desc)
            $appoint_expert->desc       =$desc;
        $appoint_expert->save();

        $newMessage = new Message();
        $newMessage->type          = 'admin';
        $newMessage->content       = $user_name . '提交了专家【'.$expert->realname.'】的预约';
        $newMessage->link_type     = 'expert_order';
        $newMessage->link_id       = $appoint_expert->id;
        $newMessage->save();

        $aaa=WechatLogin::weSendExpertMessage($user->wx_openid);

        return response()->json(['level'=>'success','message'=>'提交成功，请耐心等待',"data"=>$aaa]);
    }
}
